package com.strong.utils.security;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 自定义密码编码器
 *
 * @author Simen
 * @date 2022/01/29
 */
@Slf4j
public class Sm2PasswordEncoder implements PasswordEncoder {

    /**
     * 使用密钥对实例化
     */
    public Sm2PasswordEncoder() {
        log.info("用于SpringSecurity登录认证的Sm2PasswordEncoder加载成功");
    }

    @Override
    public String encode(CharSequence charSequence) {
        String strSign = SecurityUtils.signByUUID(charSequence.toString());
//        String strSign = HexUtil.encodeHexStr(SM2_OBJ.sign(StrUtil.utf8Bytes(charSequence), StrUtil.utf8Bytes(SecurityUtils.STR_UUID)));
        log.info("\n签名结果：\n\t原始密码：{}\n\t签名结果：{}", charSequence, strSign);
        return strSign;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (StrUtil.isAllNotBlank(rawPassword, encodedPassword)) {
            log.info("\n校验密码：\n\t提交的密码：{}\n\t密码校验码：{}", rawPassword, encodedPassword);
//            if (SM2_OBJ.verify(StrUtil.utf8Bytes(rawPassword), HexUtil.decodeHex(encodedPassword), StrUtil.utf8Bytes(SecurityUtils.STR_UUID))) {
            if (SecurityUtils.verifyByUUID(rawPassword.toString(), encodedPassword)) {
                return true;
            } else {
                throw new BadCredentialsException("账号密码验证失败 【开发提示】可能私钥文件与git上的不匹配，可以运行SecurityUtils的generateKeyPair重新生成密钥对");
            }
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        return false;
    }
}
